// server.js
const express = require('express');
const mongoose = require('mongoose');
// const app = express();
// app.use(express.json());
// const cors = require('cors')

// // 跨域
// app.use(cors())

/****************** 数据库配置 ******************/
mongoose.connect('mongodb://localhost:27017/scoreDB', { 
  useNewUrlParser: true, 
  useUnifiedTopology: true 
});

// 简化后的数据模型（无学生ID）
const ScoreSchema = new mongoose.Schema({
  month: { 
    type: String, 
    required: true, 
    unique: true, 
    match: /^20\d{4}$/ // 验证格式为20XX+两位月份
  },
  courses: [{
    name: { type: String, required: true },
    examType: { type: String, required: true },
    teachers: [{ type: String }],
    courseType: { type: String, required: true },
    credit: { type: Number, min: 0, required: true },
    gradePoint: { type: Number, min: 0, required: true },
    score: { type: Number, min: 0, max: 100, required: true }
  }],
  requiredCredits: { 
    type: Number, 
    default: 31,
    min: 0 
  }
});
const Score = mongoose.model('Score', ScoreSchema);

/****************** 统计计算函数 ******************/
const analyzeData = (courses) => {
  const totalCredits = courses.reduce((sum, c) => sum + c.credit, 0);
  const totalGradePoints = courses.reduce((sum, c) => sum + c.gradePoint, 0);
  
  return {
    totalCourses: courses.length,
    highestScore: Math.max(...courses.map(c => c.score)),
    earnedCredits: totalCredits,
    completionRate: ((totalCredits / 31) * 100).toFixed(1) + '%', // 学分完成率
    avgGradePoint: (totalGradePoints / courses.length || 0).toFixed(2)
  };
};

/****************** 核心接口 ******************/
// app.get('/api/scores', async (_, res) => {
//   try {
//     const allMonths = await Score.find().sort({ month: -1 }); // 按月份倒序
//     const result = allMonths.map(monthData => ({
//       month: monthData.month,
//       ...analyzeData(monthData.courses),
//       courses: monthData.courses // 保留详细课程数据
//     }));
    
//     res.json(result);
//   } catch (err) {
//     res.status(500).json({ error: err.message });
//   }
// });

/****************** 服务启动 ******************/
// const PORT = 3000;
// app.listen(PORT, () => {
//   console.log(`服务已启动: http://localhost:${PORT}/api/scores`);
//   console.log('测试数据插入命令(在MongoDB中执行):');
//   console.log(`
//     db.scores.insertOne({
//       month: "202401",
//       courses: [
//         {
//           name: "生产实习",
//           examType: "正常考考试",
//           teachers: ["郑巧", "赖松林"],
//           courseType: "实践必修",
//           credit: 4,
//           gradePoint: 4,
//           score: 85
//         }
//       ]
//     })`);
// });

module.exports = function (app, response) {
  app.get('/api/scores', async (_, res) => {
    try {
      const allMonths = await Score.find().sort({ month: -1 }); // 按月份倒序
      const result = allMonths.map(monthData => ({
        month: monthData.month,
        ...analyzeData(monthData.courses),
        requiredCredits: monthData.requiredCredits,
        courses: monthData.courses // 保留详细课程数据
      }));
      
      res.json({
        code: 200,
        data: result
      });
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  });
}